package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"maya-service/bll"
	"maya-service/constant"
	"maya-service/lib/authentication"
	"maya-service/model"
	"maya-service/model/po"
	"maya-service/store/redis"
	"maya-service/utils"
)

var Login = &login{}

func init() {
	RegisterRouter(Login)
}

type login struct{}

// Init
func (a *login) Init(r *gin.RouterGroup) {
	g := r.Group("/admin")
	{
		// 登录
		g.POST("/login", a.login)
	}
}

// login 登录
func (a *login) login(c *gin.Context) {
	var (
		in  = &po.LoginReq{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	// 查找结果
	find, err := bll.SysUsers.Find(c.Request.Context(), &model.SysUsersInfoRequest{
		UserName: in.UserName,
	})
	if err != nil {
		c.Error(err)
		return
	}

	if !utils.BcryptCheck(in.Password, find.Password) {
		c.Error(fmt.Errorf("账号密码不正确！"))
		return
	}

	type Ret struct {
		Token string `json:"token"`
	}

	// 生成token
	token, err := authentication.Generate(&authentication.Options{
		UserID: find.Uuid,
		Roles:  nil,
	}, constant.ExpireTime)
	if err != nil {
		c.Error(fmt.Errorf("生成token失败！"))
		return
	}

	if opts, err := authentication.Extract(token.Token); err != nil {
		c.Error(err)
		return
	} else {
		redis.KV.SetEX(c.Request.Context(), fmt.Sprintf("userData:%v", opts.UserID), utils.ToJsonString(find), constant.ExpireTime)
		redis.KV.SetEX(c.Request.Context(), fmt.Sprintf("admin_token:%v", opts.UserID), token.Token, constant.ExpireTime)
		utils.ResponseOk(c, &Ret{
			Token: token.Token,
		})
	}

}
